package com.ruoyan.controller;

import com.ruoyan.pojo.Department;
import com.ruoyan.pojo.Employee;
import com.ruoyan.pojo.Purchase;
import com.ruoyan.service.DepartmentService;
import com.ruoyan.service.EmployManageService;
import com.ruoyan.service.PurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

/**
 * @Package: com.ruoyan.controller
 * @ClassName: PurchaseController
 * @Author: ruoyan1998
 * @CreateTime: 2021/6/7 21:19
 * @Description:
 */
@Controller
public class PurchaseController
{
    @Autowired
    PurchaseService purchaseService;

    @Autowired
    EmployManageService employManageService;

    @Autowired
    DepartmentService departmentService;

    @GetMapping("/purchase")
    public String purchaseLists(Model model)
    {
        List<Purchase> purchaseList = purchaseService.queryPurchaseList();

        model.addAttribute("purchaseList",purchaseList);

        return "purchase/purchaseList";
    }

    @GetMapping("/toUpdatePur/{id}")
    public String toUpdatePur(@PathVariable("id") int id, Model model)
    {
        Purchase purchase = purchaseService.queryPurchaseListById(id);

        model.addAttribute("purchase",purchase);

        return "purchase/update";
    }

    @PostMapping("/updatePur")
    public String updatePur(Purchase purchase)
    {
        try
        {
            purchaseService.updatePurchase(purchase);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "purchase/updateError";
        }

        return "redirect:/purchase";
    }

    @GetMapping("/toAddPur")
    public String toAddPurchase()
    {
        return "purchase/add";
    }

    @PostMapping("/addPur")
    public String addPurchase(Purchase purchase,
                              @RequestParam("eid")int eid,
                              @RequestParam("did")int did)
    {
        try
        {
            Employee employee = employManageService.queryEmployeeByIdAndDid(eid, did);

            if(null == employee)
            {
                return "purchase/addError";
            }

            purchaseService.addPurchase(purchase);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "purchase/addError";
        }

        return "redirect:/purchase";
    }

    @GetMapping("/deletePur/{id}")
    public String deletePurchase(@PathVariable("id")int id)
    {
        purchaseService.deletePurchase(id);

        return "redirect:/purchase";
    }
}
